<?php

namespace common\models\shop;

use Yii;
use yii\db\Expression;

/**
 * This is the model class for table "{{%shop_coupon}}".
 *
 * @property int $id
 * @property string $name
 * @property string $description
 * @property int $scope
 * @property int $limit
 * @property int $unit
 * @property int $discount
 * @property int $radix
 * @property int $number
 * @property int $given
 * @property int $effective_time
 * @property int $expired_at
 * @property int $created_at
 * @property int $updated_at
 */
class ShopCoupon extends \common\db\ActiveRecord {

    const SCOPE_SPREAD = 1;
    const UNIT_VALUE = 0;
    const UNIT_RATIO = 1;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_coupon}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['scope', 'limit', 'unit', 'discount', 'radix', 'number', 'given', 'effective_time', 'expired_at', 'created_at', 'updated_at'], 'integer'],
            [['name', 'description'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'description' => 'Description',
            'scope' => 'Scope',
            'limit' => 'Limit',
            'unit' => 'Unit',
            'discount' => 'Discount',
            'radix' => 'Radix',
            'number' => 'Number',
            'given' => 'Given',
            'effective_time' => 'Effective Time',
            'expired_at' => 'Expired At',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public static function findByScope($scope) {
        $query = static::find()->active();
        //未发完
        $query->andWhere(['scope' => $scope]);
        //未过期
        $query->andWhere([
            'or',
            ['expired_at' => 0],
            ['>', 'expired_at', time()],
        ]);
        //未发完
        $query->andWhere([
            'or',
            ['number' => 0],
            ['<', 'number', new Expression('given')],
        ]);
        Yii::error($query->debug());
        return $query->all();
    }

}
